import time

from config import ACCOUNT, PASSWORD
from utils.utils import random_seconds, VerCodeOcr, init, update_schedule, create_loger
from playwright.sync_api import sync_playwright

Node = init()
current_course_name = Node["CurrentCourseName"]
current_node_name = Node["CourseNodeName"]
loger = create_loger('run')

with sync_playwright() as playwright:
    browser = playwright.firefox.launch(headless=False, args=['--start-maximized'])
    page = browser.new_page()
    js = """
       Object.defineProperties(navigator, {webdriver:{get:()=>false}});
       """
    page.add_init_script(js)
    page.goto('https://zswxy.yinghuaonline.com/user/login')
    time.sleep(random_seconds(1, 3))
    page.fill('input[name="username"]', ACCOUNT)
    time.sleep(random_seconds(1, 3))
    page.fill('input[name="password"]', PASSWORD)
    # do login
    is_login = False
    loger.info("开始登录")
    while not is_login:
        # image
        page.locator('#codeImg').screenshot(path='../asset/VerCode.png')
        with open('../asset/VerCode.png', 'rb') as f:
            img_content = f.read()
        loger.info("开始识别登录验证码")
        result = VerCodeOcr(img_content)
        # result = input('test:')
        loger.info(f"识别登录验证码结果: {result}")
        page.fill('input[name="code"]', result)
        time.sleep(random_seconds(1, 3))
        # 点击登录 判断验证码是否正确
        loger.info("点击登录")
        page.locator('input[type="submit"]').click()
        # 等待1.5秒是否出现弹窗
        time.sleep(1.5)
        dialog = page.query_selector('div[type="dialog"]')
        if not dialog:
            loger.info("验证码正确,登录成功")
            break
        else:
            loger.error("验证码错误,开始重新登录")
            page.locator('a[class="layui-layer-btn0"]').click()
    time.sleep(1)
    # 查询课程
    courses = page.query_selector_all('div[class="user-course"] > div')
    if current_course_name:
        for course in courses:
            link_element = course.query_selector('div[class="name"] > a')
            name = link_element.inner_text()
            if name == current_course_name:
                link_element.click()
                break
    else:
        first_course = courses[0]
        link_element = first_course.query_selector('div[class="name"] > a')
        link_element.click()

    time.sleep(2)
    # 点击继续学习按钮
    page.query_selector('div[class="ncoursecon-intro"]  div[class="item"] > a[class="btn1"]').click()
    time.sleep(random_seconds(2, 4))
    node_name = ""
    while True:
        nodes = page.query_selector_all('div[class="detmain-navlist"] div[class="item"] a')
        time.sleep(2)
        if current_node_name:
            for i in range(len(nodes)):
                node = nodes[i]
                node_name = node.inner_text()
                if current_node_name == node_name:
                    current_node_name = nodes[i + 1].inner_text()
                    link = "https://zswxy.yinghuaonline.com/" + node.get_attribute("href")
                    page.goto(link)
                    break
        else:
            node = nodes[0]
            current_node_name = node.inner_text()
            link = "https://zswxy.yinghuaonline.com/" + node.get_attribute("href")
            page.goto(link)
        time.sleep(random_seconds(2, 4))

        while True:
            # 判断验证码提交按钮是否存在
            time.sleep(3)
            btn = page.query_selector('a[class="layui-layer-btn0"]')
            if btn:
                loger.warning("跳转到章节页出现验证码")
                ver_code_element = page.query_selector(".layui-layer-wrap > div:nth-child(2) > input:nth-child(2)")
                page.query_selector('img[id="codeImg"]').screenshot(path='../asset/VideoVerCode.png')
                loger.info("开始识别验证码")
                result = VerCodeOcr(open('../asset/VideoVerCode.png', 'rb').read())
                loger.info(f"验证码识别结果: {result}")
                ver_code_element.fill(result)
                page.locator('a[class="layui-layer-btn0"]').click()
            else:
                break
        # 点击播放
        time.sleep(1)
        video = page.wait_for_selector('video')
        page.query_selector_all('#videoContent > div > div> canvas')[0].click()
        while True:
            # 判断验证码提交按钮是否存在
            time.sleep(3)
            btn = page.query_selector('a[class="layui-layer-btn0"]')
            if btn:
                loger.warning("点击播放视频后出现验证码")
                ver_code_element = page.query_selector(".layui-layer-wrap > div:nth-child(2) > input:nth-child(2)")
                page.query_selector('img[id="codeImg"]').screenshot(path='../asset/VideoVerCode.png')
                loger.info("开始识别验证码")
                result = VerCodeOcr(open('../asset/VideoVerCode.png', 'rb').read())
                loger.info(f"验证码识别结果: {result}")
                ver_code_element.fill(result)
                page.locator('a[class="layui-layer-btn0"]').click()
            else:
                break
        loger.info(f'{node_name} 开始播放')
        video.evaluate("(video) => video.play()")
        # 等待视频播放完毕
        page.wait_for_function('() => document.querySelector("video").ended', timeout=20000000)

        loger.info(f'{node_name} 播放完毕')

        current_course_name = Node["CurrentCourseName"]
        update_schedule(current_course_name, current_node_name)
